const Service = require('egg').Service;
const jsonwebtoken = require('jsonwebtoken');

class StudentService extends Service {
  // 注册的业务逻辑
  async register() {
    const { ctx } = this;
    const { name, stuId, status, password } = ctx.request.body;
    const sql = `insert into student (name, stuId, password, status)
     values ('${name}', '${stuId}', '${ctx.helper.getPassword(password)}', '${status}');`
    const data = await ctx.app.mysql.query(sql);
    return await {
      data: data.insertId || {}
    }
  }

  // 登陆的业务逻辑
  async login() {
    const { ctx } = this;
    // 获取前端登陆参数  学生id 和 学生密码
    const loginRes = ctx.request.body;
    // 根据id查
    const sql = `select stuId, password, status from student where 
    stuId='${loginRes.stuId}' and password='${ctx.helper.getPassword(loginRes.password)}';`
    const data = await ctx.app.mysql.query(sql);
    if (data.length) {
      const { stuId, password, status } = data[0]
      console.log('stuatus:', status)
      const token = jsonwebtoken.sign({ stuId, password, status }, ctx.app.config.keys, { expiresIn: '24h' });
      return await {
        token,
        code: 0,
        msg: 'success'
      }
    } else {
      return await {
        msg: '找不到对象',
        code: -1
      }
    }

  }

  // 根据学生id查找学生数据   
  async findByStuId() {
    // 这个是对student表操作 分页 操作
    const { ctx } = this;
    const { page, size } = ctx.query;
    // 0 5  1 5 2  5   
    // 0 * 5 = 0
    // 1 * 5 = 5
    // 2 * 5 = 10  
    const sql = `select id, name, stuId, status 
    from student limit ${size} offset ${page * size};`
    const data = await ctx.app.mysql.query(sql);
    return await data
  }
}

module.exports = StudentService
